using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.Permissions;
using System.Diagnostics;

namespace RBAC.Api.Writh.CommandHandler.Permissions
{
    /// <summary>
    /// 修改权限状态处理程序
    /// </summary>
    public class UpdatePermissionStateCommandHandler : IRequestHandler<UpdatePermissionStateCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<Permission> dal;
        private readonly ILogger<UpdatePermissionStateCommandHandler> logger;

        public UpdatePermissionStateCommandHandler(IBaseRepositry<Permission> baseRepositry, ILogger<UpdatePermissionStateCommandHandler> logger)
        {
            dal = baseRepositry;
            this.logger = logger;
        }

        public async Task<APIResult<object>> Handle(UpdatePermissionStateCommand request, CancellationToken cancellationToken)
        {
            var stopwatch = Stopwatch.StartNew();
            APIResult<object> result = new APIResult<object>();
            
            try
            {
                logger.LogInformation("开始处理修改权限状态请求，权限ID: {Id}", request.Id);
                
                // 获取权限实体
                var permission = dal.GetAll().FirstOrDefault(p => p.Id == request.Id);
                if (permission == null)
                {
                    result.Code = ResultCode.Fail;
                    result.Message = $"未找到ID为{request.Id}的权限";
                    logger.LogWarning("修改权限状态失败：未找到对应权限, ID: {Id}", request.Id);
                    return result;
                }

                // 修改状态
                permission.State = request.State;
            //    permission.State=true; // 确保状态为启用
                permission.ModifyTime = DateTime.Now;
                
                await dal.Update(permission);
                
                result.Code = ResultCode.Success;
                result.Message = $"修改权限状态成功，当前状态: {(request.State ? "启用" : "禁用")}";
                logger.LogInformation("修改权限状态成功, ID: {Id}, 新状态: {State}", request.Id, request.State);
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.Fail;
                result.Message = $"修改权限状态失败: {ex.Message}";
                logger.LogError(ex, "修改权限状态出现异常, ID: {Id}, 错误: {Message}", request.Id, ex.Message);
            }
            finally
            {
                stopwatch.Stop();
                logger.LogInformation("处理修改权限状态请求完成, 耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }

            return result;
        }
    }
} 